﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ModbusTestTool.Singeltons;
using System.Xml.Serialization;
using System.IO;
using System.IO.Ports;

namespace ModbusTestTool.UI
{
    public partial class SettingsPane : UserControl
    {
        public SettingsPane()
        {
            InitializeComponent();

            Singeltons.Settings.state currentstate = Settings.Instance.State;

            List<COMPortInfo> comInfo = new List<COMPortInfo>();
            comInfo = COMPortInfo.GetCOMPortsInfo();

            string[] comports = SerialPort.GetPortNames();
            string[] comport_plus_desc = new string[comInfo.Count];

            for (int i = 0; i < comInfo.Count; i++)
            {
                comport_plus_desc[i] = comInfo[i].Name + " " + comInfo[i].Description;

            }




            //comboBox1.DataSource = SerialPort.GetPortNames();

            comboBox1.DataSource = comport_plus_desc;

            textBox1.Text = currentstate.modbusId.ToString();
            textBox2.Text = currentstate.baudSpeed.ToString();
           

            //int index = Array.IndexOf(SerialPort.GetPortNames(), currentstate.comPort);

            int index = findIndex(currentstate.comPort, comport_plus_desc);

            if (index != -1)
            {
                comboBox1.SelectedIndex = index;
            }
        }

        int findIndex(string item, String[] list)
        {
            for (int i = 0; i < list.Length; i++)
            {
                if (list[i].Contains(item))
                    return i;
            }
            return -1;

        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            
        }

        private void button1_Click(object sender, EventArgs e)
        {
            lock(Settings.lockVar){
                Settings.Instance.State.comPort = ((string) (comboBox1.SelectedValue)).Split(' ')[0];
                Settings.Instance.State.modbusId = byte.Parse(textBox1.Text);
                Settings.Instance.State.baudSpeed = int.Parse(textBox2.Text);

                Settings.Instance.State.serialOrTcpSelect = Settings.serialOrTcp.serial;
                Settings.Instance.updatePort();
                Settings.Instance.SaveCurrentState();
                //Settings.Instance.SetupModbusPorts();
            }
            
            //((string) comboBox1.SelectedValue).Split(' '))[0],byte.Parse(textBox1.Text),int.Parse(textBox2.Text)
        }
    }
}
